package com.lxdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.lxdp.dto.Result;
import com.lxdp.dto.ScrollResult;
import com.lxdp.dto.UserDTO;
import com.lxdp.entity.Blog;
import com.lxdp.entity.Follow;
import com.lxdp.entity.User;
import com.lxdp.mapper.BlogMapper;
import com.lxdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxdp.service.IFollowService;
import com.lxdp.service.IUserService;
import com.lxdp.utils.RedisConstants;
import com.lxdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hong
 * @since 2023-04-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;
    @Autowired
    private IFollowService followService;

    @Override
    public Result likeBlog(Long id) {
        Long userID = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        String value =userID.toString();
        Double score = stringRedisTemplate.opsForZSet().score(key, value);
        if(score != null){
            this.update()
                    .setSql("liked = liked - 1")
                    .eq("id",id).update();
            stringRedisTemplate.opsForZSet().remove(key, value);
        }else {
            this.update()
                    .setSql("liked = liked + 1")
                    .eq("id",id).update();
            stringRedisTemplate.opsForZSet().add(key, value,System.currentTimeMillis());
        }

        return Result.ok();
    }

    @Override
    public Result queryLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (set.isEmpty() || set == null) {
            return Result.ok(Collections.emptyList());
        }

        List<Long> list = set.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", list);
        List<UserDTO> dtoList = userService.lambdaQuery().in(User::getId,list).last("ORDER BY FIELD(id,"+idStr+")").list()
                .stream().map(
                user ->{
                    UserDTO userDTO = new UserDTO();
                    BeanUtils.copyProperties(user, userDTO);
                    return userDTO;
                }).collect(Collectors.toList());
        return Result.ok(dtoList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        boolean save = save(blog);
        if(save){
            List<Follow> list = followService.lambdaQuery()
                    .eq(Follow::getFollowUserId, user.getId()).list();
            for (Follow follow : list) {
                Long userId = follow.getUserId();
                String key = "feed:" + userId;
                stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
            }
            return Result.ok(blog.getId());
        }
        return Result.fail("笔记发布失败");
    }

    @Override
    public Result queryBlogFollow(Long max, Integer offset) {
        UserDTO user = UserHolder.getUser();
        String key = "feed:" + user.getId();
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(typedTuples.isEmpty() || typedTuples == null){
            return Result.ok();
        }
        ArrayList ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        String idStr = StrUtil.join(",", ids);
        List<Blog> list = this.lambdaQuery().in(Blog::getId, ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : list) {
            isLiked(blog);
        }
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(list);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
    private void isLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return;
        }
        Long id = user.getId();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), id.toString());
        blog.setIsLike(BooleanUtil.isTrue(score != null));
    }

}
